import redis
import pickle
from loguru import logger
class Redis_Utils():
    def __init__(self,global_config):
        self._global_config=global_config
        self._redis_pool = redis.ConnectionPool(**self._global_config.REDIS_CONFIG)


    def get_redis_pool(self):
        '''
        初始化 redis poolDB
        :return:  _redis_pool
        '''
        # pass
        # self._redis_pool = redis.ConnectionPool(**self._global_config.REDIS_CONFIG)
        return self._redis_pool

    def set_value_use_pickle(self,key,value,ex=None):
        '''
        不同类型结果集，用pickle转化，存入redis
        :return:
        '''
        rds=redis.Redis(connection_pool=self._redis_pool)
        value=pickle.dumps(value)
        if len(value)/1024/1024 > 500 :
            logger.info('{}数据大小超过512MB,不在Redis中进行缓存！！！'.format(key))
        else:
            rds.set(key,value,ex)
        pass

    def get_value_return_pickle(self,key):
        rds=redis.Redis(connection_pool=self._redis_pool)
        value=rds.get(key)
        if value is None :
            return None
        else:
            res=pickle.loads(value)
            return res

    # def redis(self):
    #     pass
    #     r=redis.Redis(connection_pool=self._redis_pool)

if __name__ == '__main__':
    pass
    # from applications.configs import global_config
    # config=global_config['Dev']
    # # print(config.REDIS_CONFIG)
    # # pass
    # a=Redis_Utils(config)
    # r=redis.Redis(connection_pool=a.get_redis_pool())
    # r.set('gender', 'male')  # key是"gender" value是"male" 将键值对存入redis缓存
    # print(r.get('gender'))  # gender 取出键male对应的值